package com.zws.cucumber.util;

import com.zws.cucumber.util.colorfullog.ZwsColorfulLogger;
import org.slf4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.util.*;

/**
 * author: zws
 */
public class ZwsHttpUtil {

    public static final Map<String, Set<String>> customizedHeaders = new HashMap<>();
    public static final Set<String> removedHeaders = new HashSet<>();
    private static final Logger logger = ZwsColorfulLogger.of(ZwsHttpUtil.class);

    public static HttpHeaders buildHttpHeaders() {
        return buildHeadersWithoutAuthorization();
    }

    public static HttpHeaders buildHeadersWithoutAuthorization() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        buildCustomizedHeaders(headers);
        return headers;
    }

    public static void prepareHeader(String key, String val) {
        Set<String> valSet = customizedHeaders.computeIfAbsent(key, k -> new HashSet<>());
        valSet.add(val);
    }

    public static void prepareHeaderIfAbsent(String key, String val) {
        Set<String> valSet = customizedHeaders.computeIfAbsent(key, k -> new HashSet<>());
        if (valSet.isEmpty()) {
            valSet.add(val);
        }
    }

    public static void removeHeader(String key) {
        removedHeaders.add(key);
    }

    private static void buildCustomizedHeaders(HttpHeaders headers) {
        if (customizedHeaders.size() > 0) {
            customizedHeaders.forEach((key, vals) -> {
                // customized override the origin
                headers.remove(key);
                // add customized
                for (String v : vals) {
                    headers.add(key, v);
                }
            });
            customizedHeaders.clear();
        }
        removedHeaders.forEach(headers::remove);
        removedHeaders.clear();
    }

    public static Map<String, Set<String>> getCustomizedHeaders() {
        return new HashMap<>(customizedHeaders);
    }

    public static void setCustomizedHeaders(Map<String, Set<String>> customizedHeaders) {
        ZwsHttpUtil.customizedHeaders.clear();
        ZwsHttpUtil.customizedHeaders.putAll(customizedHeaders);
    }

    public static Set<String> getRemovedHeaders() {
        return new HashSet<>(removedHeaders);
    }

    public static void setRemovedHeaders(Set<String> removedHeaders) {
        ZwsHttpUtil.removedHeaders.clear();
        ZwsHttpUtil.removedHeaders.addAll(removedHeaders);
    }

}
